<?php

namespace app\admin\controller\subjectlv;

use app\common\controller\Backend;
use fast\Tree;
/**
 * 
 *
 * @icon fa fa-file
 */
class Subjectlv extends Backend
{
    
    /**
     * Subjectlv模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status","class_type","liststree"];
    protected $noNeedLogin=["lists","status","class_type","liststree"];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Subjectlv');
        $this->modelValidate = true;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 调试日志
            error_log("Subjectlv Index - city_id: $city_id, school_id: $school_id");

            $total = $this->model
                ->where($where);
                
            // 添加城市过滤
            if (!empty($city_id)) {
                $total = $total->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤
            if (!empty($school_id)) {
                $total = $total->where("school_id", "=", $school_id);
            }
            
            $total = $total->where("status", "<>", -1)
                ->count();

            $list = $this->model
                ->where($where);
                
            // 添加城市过滤
            if (!empty($city_id)) {
                $list = $list->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            
            // 添加学校过滤
            if (!empty($school_id)) {
                $list = $list->where("school_id", "=", $school_id);
            }
            
            $list = $list->where("status", "<>", -1)
                ->order($sort, $order)
                ->limit($offset, 500)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();
            $tree = Tree::instance();
            $tree->init($list, 'pid');
            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
            $data = array();
            for ($i = 0; $i < count($list); $i++) {
                $v = $list[$i];
                if($v['level']==0) {
                    $v['name'] = "<span class='lv1'>{$v['name']}</span>";
                }elseif($v['level']==1) {
                   // $v['name'] = "<span class='lv2'>{$v['name']}</span>";
                    $v['name'] = preg_replace_callback("/^(\&nbsp\;)((?:\s|├|\&nbsp\;|│|├|└)*?)(.*)$/Uisx",function ($em){
                        return "{$em[1]}".str_replace("&nbsp;","&nbsp;&nbsp;",$em[2])."<span class='lv2'>{$em[3]}</span>";
                    },$v['name']);
                }elseif($v['level']==2) {
                    $v['name'] = preg_replace_callback("/^(\&nbsp\;)((?:\s|\&nbsp\;|\│|\├|└)*?)(.*)$/Uisx",function ($em){
                        return "{$em[1]}".str_replace("&nbsp;","&nbsp;&nbsp;",$em[2])."<span class='lv4'>{$em[3]}</span>";
                    },$v['name']);
                }
                $data[] = [
                    'id' => $v['id'],
                    'parent' => $v['pid'] ? $v['pid'] : '#',
                    'name' => $v['name'],
                    'type' => $v['type'],
                    'addresslv_id' => $v['addresslv_id'],
                    'status' => $v['status'],
                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id']),
                    'city_id' => model("Cityarea")->getCity_idTextAttr($v['city_id']),
                ];
            }

            for($i=0;$i<count($list);$i++){
//                $list[$i]['province_id']=model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id']);
//                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id']);
//                $list[$i]['district_id']=model('Cityarea')->getDistrict_idTextAttr($list[$i]['district_id']);
//                $list[$i]['province_id']=preg_replace("/\/$/","",model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id'])."/".$list[$i]['city_id']."/".$list[$i]['district_id']);
//                $list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
                //$v['pid']=$this->model->getPidTextAttr($v['pid'],$v);
                $list[$i]['pid']=$this->model->getPidTextAttr($list[$i]['pid'],$list[$i]);
            }

            $result = array("total" => $total, "rows" => $data);
            return json($result);
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 重新计算并更新所有节点的level值
     */
    private function updateAllLevels()
    {
        // 获取所有记录
        $list = $this->model->order('id asc')->select();
        $list = collection($list)->toArray();
        
        // 构建树结构
        $tree = Tree::instance();
        $tree->init($list, 'pid');
        $treeList = $tree->getTreeList($tree->getTreeArray(0), 'name');
        
        // 更新每个节点的level值
        foreach ($treeList as $node) {
            $this->model->where('id', $node['id'])->update(['level' => $node['level']]);
        }
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 限制学科层级不能超过两级
                if (isset($params['level']) && $params['level'] > 2) {
                    return json(['code'=>0,'msg'=>'学科最多只能分为两级']);
                }
                
                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }
                
                // 调试日志
                error_log("Subjectlv Add - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));
                
                // 默认状态为开
                $params['status'] = 1;
                // 不再依赖subject_id，直接用pid
                // unset($params['subject_id']);
                unset($params['delete_time']);
                unset($params['update_time']);
                $result = $this->model->allowField(true)->save($params);
                if ($result !== false) {
                    // 重新计算并更新所有节点的level值
                    $this->updateAllLevels();
                    $this->success("添加成功",null,["refresh"=>1]);
                } else {
                    $this->error($this->model->getError());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('admin', $_SESSION['think']['admin']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 限制学科层级不能超过两级
                if (isset($params['level']) && $params['level'] > 2) {
                    return json(['code'=>0,'msg'=>'学科最多只能分为两级']);
                }
                
                // 自动插入session中的城市和学校ID（如果当前记录没有设置的话）
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    if (empty($row['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    if (empty($row['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                }
                
                // 调试日志
                error_log("Subjectlv Edit - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));
                
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    // 不再依赖subject_id，直接用pid
                    // unset($params['subject_id']);
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        // 重新计算并更新所有节点的level值
                        $this->updateAllLevels();
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('admin', $_SESSION['think']['admin']);
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function lists($ids = NULL){
        $where="where 1=1";
//        if($_SESSION['think']['admin']['group_id']!=1){
//            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
//        }
        $page=1;
        $pagesize=50;
        $pid=null;
        $ppid=null;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where status=1";
//                if(isset($_REQUEST['school_id'])&&$_REQUEST['school_id']>0){
//                    $where.=" and school_id=".$_REQUEST['school_id'];
//                }elseif($_SESSION['think']['admin']['school_id']){
//                    $where.=" and school_id=".$_SESSION['think']['admin']['school_id'];
//                }
                if(isset($_REQUEST['subject_lv'])&&$_REQUEST['subject_lv']>0){
                    $ids = [$_REQUEST['subject_lv']];
                    $parent = model("Subjectlv")->field("pid")->where("id", "=", $_REQUEST['subject_lv'])->find();
                    $pparent = model("Subjectlv")->field("pid")->where("id", "=", $parent['pid'])->find();
                    $children = model("Subjectlv")->field("id")->where("pid", "=", $_REQUEST['subject_lv'])->select();
                    // 递归获取所有子孙节点
                    $pid=$parent['pid'];
                    $ppid=$pparent['pid'];
                    if($ppid>0){
                        $children = model("Subjectlv")->field("id")->where("pid", "=", $ppid)->select();
                    }
                    while (!empty($children)) {
                        $childIds = [];
                        foreach ($children as $child) {
                            $childIds[] = $child['id'];
                        }
                        $ids = array_merge($ids, $childIds);
                        $children = model("Subjectlv")->whereIn("pid", $childIds)->select();
                    }
                    $ids = array_merge($ids, $children);
                    $where.= " and id in (".implode(',', $ids).")";
                    if($_REQUEST['subject_lv']){
                        $r_name_address_lv = model("Subjectlv")->field("id,name")->where("id", "=", $_REQUEST['subject_lv'])->select();
                    }elseif($_REQUEST['address_lv']==0){
                        $r_name_address_lv = model("Subjectlv")->field("id,name")->where("id", "=", $_REQUEST['address_lv'])->select();
                    }
                }else if(isset($_REQUEST['address_lv'])&&$_REQUEST['address_lv']>0){
                    // 获取指定节点及其所有子孙节点
                    $ids = [$_REQUEST['address_lv']];
                    $children = model("Subjectlv")->field("id")->where("pid", "=", $_REQUEST['address_lv'])->select();
                    
                    // 递归获取所有子孙节点
                    while (!empty($children)) {
                        $childIds = [];
                        foreach ($children as $child) {
                            $childIds[] = $child['id'];
                        }
                        $ids = array_merge($ids, $childIds);
                        $children = model("Subjectlv")->whereIn("pid", $childIds)->select();
                    }
                    
                    $where.= " and id in (".implode(',', $ids).")";
                    if($_REQUEST['subject_lv']){
                        $r_name_address_lv = model("Subjectlv")->field("id,name")->where("id", "=", $_REQUEST['subject_lv'])->select();
                    }elseif($_REQUEST['address_lv']==0){
                        $r_name_address_lv = model("Subjectlv")->field("id,name")->where("id", "=", $_REQUEST['address_lv'])->select();
                    }
                }
                if(isset($_REQUEST['level'])&&$_REQUEST['level']>0){
                    $where.=" and level=".$_REQUEST['level'];
                }
            }
        }

        $sql="select id,name name,pid,title,status,level from dev002_gxyusheng.fa_subject_lv $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);
        if(isset($_REQUEST['school_id'])&&$_REQUEST['school_id']>0) {
            $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
            $school_id=$_REQUEST['school_id'];
        }else{
            $r_name = model("School")->field("id,name")->where("id", "=", $_SESSION['think']['admin']['school_id'])->select();
            $school_id=$_SESSION['think']['admin']['school_id'];
        }

        if(isset($r_name)&& !empty($r_name) && isset($r_name_address_lv)) {
            $name = $r_name[0]['name'] . $r_name_address_lv[0]['name'] . "学科";
        } else {
            $name = "学科";
        }

        if (empty($list)) {
            $data = array(
                "type" => "file",
                "pid" => 0,
                "name" => $name,
                "title" => $name,
                "ismenu" => 0,
                "createtime" => time(),
                "updatetime" => time(),
                "status" => 1,
                "school_id" => $school_id,
                "addresslv_id" => $_REQUEST['address_lv'],
            );
            $this->model->insertUpdate($data,["name","school_id","addresslv_id" ]);
        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.fa_subject_lv where pid=0";
//        $list2 = db()->query($sql);
//        $pid=$list2[0]["id"];
//        $where="where city_id='{$_SESSION['think']['admin']['city_id']}' and school_id='{$_SESSION['think']['admin']['school_id']}' and status=1";
//        if(isset($_REQUEST['level'])&&$_REQUEST['level']>0){
//            $where.=" and level=".$_REQUEST['level'];
//        }
//        $sql2="select id,pid,name,title,status from dev002_gxyusheng.fa_subject_lv $where";
//        $list = db()->query($sql2);
        $tree = Tree::instance();
        $tree->init($list, 'pid');
        if($ppid>0){
            $list = $tree->getTreeList($tree->getTreeArray($ppid), 'name');
        }else if(isset($_REQUEST['address_lv'])){
            $list = $tree->getTreeList($tree->getTreeArray($pid), 'name');
        }elseif($pid>0){
            $list = $tree->getTreeList($tree->getTreeArray($pid), 'name');
        }
        $data = array();
        for ($i = 0; $i < count($list); $i++) {
            $v = $list[$i];
            if(array_key_exists("level",$v)) {
                if ($v['level'] == 0) {
                    $v['name'] = "<span class='lv1'>{$v['name']}</span>";
                } elseif ($v['level'] == 1) {
                    $v['name'] = "<span class='lv2'>{$v['name']}</span>";
                } elseif ($v['level'] == 2) {
                    $v['name'] = "<span class='lv3'>{$v['name']}</span>";
                }
            }
            $data[] = [
                'id' => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'name' => $v['name'],
                //'level' => $v['level'],
                //'type' => $v['type'],
                'status' => $v['status'],
                'haschild' => $v['haschild'],
            ];
        }
        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_subject_lv $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function class_type(){
            $where = "where 1=1";
            if ($_SESSION['think']['admin']['group_id'] == 2 || $_SESSION['think']['admin']['group_id'] == 8) {
                $where .= " and city_id='{$_SESSION['think']['admin']['city_id']}'";
            }
            $page = 1;
            $pagesize = 50;
            if ($this->request->isAjax()) {
                if ($this->request->request('keyField')) {
                    $keyField = $this->request->request("keyField");
                    $keyValue = $this->request->request("keyValue");
                    $page = $this->request->request("pageNumber");
                    $page = ($page == null) ? 1 : $page;
                    $pagesize = $this->request->request("pageSize");
                    $pagesize = ($pagesize == null) ? 10 : $pagesize;
                    if ($keyValue != "") {
                        $nn = preg_split("/\,/", $keyValue);
                        for ($i = 0; $i < count($nn); $i++) {
                            $where .= " and $keyField='{$nn[$i]}'";
                        }
                    }
                }
            }
            $sql = "select id,name name from dev002_gxyusheng.fa_subject_class_type $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
            $list = db()->query($sql);
            $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_subject_class_type $where")[0];
            echo json_encode(array("list" => $list, "total" => $total['c']));
            exit;


    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    /**
     * 获取学科层级树形结构
     */
    public function liststree()
    {
        $list = $this->model->where('status', 1)->where('status', 1)->order('weigh desc,id asc')->select();
        $list = collection($list)->toArray();
        $tree = \fast\Tree::instance();
        $tree->init($list, 'pid');
        $treeList = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $data = [];
        foreach ($treeList as $v) {
            // 只允许两级
            //if ($v['level'] >= 0) continue;
            $name = strip_tags($v['name']);
            if ($v['level'] == 1) {
                $name = "<span class='lv4'>" . $name . "</span>";
            }
            $data[] = [
                'id' => $v['id'],
                'pid' => $v['pid'],
                'name' => $name,
                'level' => $v['level'],
            ];
        }
        return json(['list' => $data, 'code' => 1]);
    }



}